<template>
  <div class="header-container">
    <nav-bar :title="'购物车'"></nav-bar>
  </div>
  <div class="main-container">
    <van-list
      v-model:loading="listLoading"
      :finished="listFinished"
      finished-text="没有更多了"
      @load="onListLoad"
    >
      <template v-if="cartItems && cartItems.length > 0">
        <van-checkbox-group
          ref="checkboxGroup"
          v-model="checkeds"
          @change="checkedsChanged"
        >
          <template v-for="item of cartItems" :key="item.id">
            <van-swipe-cell>
              <van-card
                :num="item.quantity"
                :price="item.price"
                :title="item.productName"
                :thumb="item.productImgUrl"
                style="margin-top: 5px; margin-bottom: 5px"
              >
                <template #thumb>
                  <van-row style="height: 100%; align-items: center">
                    <van-col span="8">
                      <van-checkbox :name="item.id" checked-color="#ee0a24" />
                    </van-col>
                    <van-col span="16">
                      <van-image
                        :src="item.productImgUrl"
                        style="width: 100%"
                      ></van-image>
                    </van-col>
                  </van-row>
                </template>
                <template #num>
                  <van-stepper
                    integer
                    :min="1"
                    :model-value="item.quantity"
                    :name="item.id"
                    button-size="22"
                    disable-input
                    async-change
                    @change="changeQuantity($event, item)"
                  />
                </template>
              </van-card>
              <template #right>
                <van-button
                  square
                  icon="delete"
                  type="danger"
                  style="height: 100%"
                  @click="remove($event, item)"
                />
              </template>
            </van-swipe-cell>
          </template>
        </van-checkbox-group>

        <van-submit-bar
          :price="totalAmount"
          button-text="结算"
          @submit="submit"
          :disabled="checkeds == null || checkeds.length <= 0"
          style="bottom: 50px"
        >
          <van-checkbox
            v-model="checkedAll"
            checked-color="#ee0a24"
            @change="checkAll"
          >
            全选
          </van-checkbox>
        </van-submit-bar>
      </template>
      <template v-else>
        <van-empty />
      </template>
    </van-list>
  </div>
  <div class="footer-container">
    <tab-bar activeItem="cart" />
  </div>
</template>

<script lang="ts">
import {
  computed,
  defineComponent,
  onMounted,
  reactive,
  ref,
  toRefs,
} from "vue";
import NavBar from "@/components/NavBar.vue";
import TabBar from "@/components/TabBar.vue";
import OmsCartItem from "@/entity/OmsCartItem";
import Page from "@/entity/Page";
import { useRoute, useRouter } from "vue-router";
import cartItemService from "@/services/cart-item.service";
import { AxiosError } from "axios";
import { Toast } from "vant";
import OmsCartItemCreationParam from "@/entity/OmsCartItemCreationParam";
import { CheckboxGroup } from "vant";
import OrderType from "@/entity/OmsOrderType";

type StateType = {
  listLoading: boolean;
  listFinished: boolean;
  cartItems: OmsCartItem[];
  page?: Page<OmsCartItem> | null;
  checkeds: number[];
  checkedAll: boolean;
};

export default defineComponent({
  components: {
    NavBar,
    TabBar,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const state = reactive<StateType>({
      listLoading: false,
      listFinished: false,
      cartItems: new Array<OmsCartItem>(),
      page: null,
      checkeds: [],
      checkedAll: false,
    });
    const checkboxGroup = ref<typeof CheckboxGroup>();

    onMounted(() => {
      load();
    });

    const totalAmount = computed(() => {
      const selections = state.cartItems.filter((it) =>
        state.checkeds.includes(it.id)
      );
      let totalAmount = 0;
      selections.forEach((it) => {
        if (it == null || it.price == null || it.quantity == null) {
          return;
        }
        // 提交订单栏组件单位是 分
        totalAmount += it.price * it.quantity * 100;
      });

      return totalAmount;
    });

    const load = async (no?: number, size?: number) => {
      try {
        state.listLoading = true;
        const page =
          no == null
            ? await cartItemService.page()
            : await cartItemService.page(no, size);
        state.page = page;
        state.cartItems = [...state.cartItems, ...page.content];
        state.listFinished = state.page.last;
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
        state.listLoading = false;
      }
    };

    const onListLoad = () => {
      load(
        state.page ? state.page.number + 1 : undefined,
        state.page ? state.page.size : undefined
      );
    };

    const changeQuantity = async (val: number, item: OmsCartItem) => {
      const param: OmsCartItemCreationParam = {
        productId: item.productId,
        quantity: item.quantity ? val - item.quantity : 1,
      };
      const id = await cartItemService.createOrUpdate(param);
      item.quantity = val;
    };

    const checkedsChanged = (names: number[]) => {
      const selections = state.cartItems.filter((it) => names.includes(it.id));
    };

    const checkAll = (checked: boolean) => {
      checkboxGroup.value?.toggleAll(checked);
    };

    const remove = async (evt: any, cartItem: OmsCartItem) => {
      try {
        const items = await cartItemService.remove([cartItem.id]);
        state.cartItems = [];
        if (state.page != null && state.page.numberOfElements != null) {
          await load(1, state.page.numberOfElements - 1);
          const idx = state.checkeds.indexOf(cartItem.id);
          if (idx != -1) {
            state.checkeds.splice(idx, 1);
          }
        }
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
      }
    };

    const submit = () => {
      try {
        const selections = state.cartItems.filter((it) =>
          state.checkeds.includes(it.id)
        );
        router.push({
          path: "/order-preview",
          query: {
            cartItemIds: selections.map((it) => it.id),
            orderType: OrderType.FROM_CART,
          },
        });
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
      }
    };

    return {
      ...toRefs(state),
      checkboxGroup,
      totalAmount,
      onListLoad,
      changeQuantity,
      checkedsChanged,
      checkAll,
      remove,
      submit,
    };
  },
});
</script>

<style scoped></style>
